package com.vipshop.util.factory;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.vipshop.common.Config;
import com.vipshop.common.Configure;


import android.text.TextUtils;



public class ImageUrlFactory {

	private final static String SERVER_URL = "pic1.vipshop.com";

	public final static int BRANK = 0;

	public final static int GOODS	 = 1;

	public final static int SMALL = 2;

	public final static int BIG = 3;

	public final static int CHART = 4;

	public final static int LOGO = 5;

	private static IImageSuffer suf;

	private static LowImageSuffer ls;

	private static MiddleImageSuffer ms;

	private static HighImageSuffer hs;

	public static String notify(String url,int type){
		try{
		if(Config.ENABLE_IMAGE_SERVER &&isURL(url)){

			String s3 = url.replace(getHost(url), SERVER_URL);

			String suf = getSuffix(s3);
			return s3.substring(0,s3.lastIndexOf(suf))+getSuffix(type,suf)+"@"+url;
		}
		}catch (Exception e){
			return url;
		}
		return url;
	}
	public static String getNotify(String url,int type){
		try{
		if(Config.ENABLE_IMAGE_SERVER &&isURL(url)){

			String s3 = url.replace(getHost(url), SERVER_URL);

			String suf = getSuffix(s3);
			return s3.substring(0,s3.lastIndexOf(suf))+getSuffix(type,suf);
		}
		}catch (Exception e){
			return url;
		}
		return url;
	}

	private static String getSuffix(int type,String suffix){
		suf = null;
		int width = (int)Configure.screenWidth;

		if(width  <= 320){
			if(ls==null) ls = new LowImageSuffer();
			suf = ls;
		}else if (width >= 540){
			if(hs==null) hs = new HighImageSuffer();
			suf = hs;
		}else{
			if(ms==null) ms = new MiddleImageSuffer();
			suf = ms;
		}
		return suf.getSuffer(type)+suffix;
	}

	public static String getSuffix(String filename)
	{
		try {
			int beginIndex = filename.lastIndexOf(".");
			String result = filename.substring(beginIndex).trim();
			int length = result.length();
			if(length > 0 && length < 5){
				return result;
			}else{
				return "";
			}
		} catch (Exception e) {
			return "";
		}
	}

	private static final Pattern PATTERN = Pattern.compile("(http://|https://){1}[\\w\\.\\-/:]+");
	public static boolean isURL(String url){
		if(!TextUtils.isEmpty(url) &&  PATTERN.matcher(url).find()){
			return true;
		}else{
			return false;
		}
	}

	public static String getHost(String url) throws MalformedURLException{
		return new URL(url).getHost();
	}




}
